package com.example.webchar.webchar.service.serverimpl;

import com.example.webchar.webchar.mapper.master.UserMapperMaster;
import com.example.webchar.webchar.mapper.slave.UserMapperSlave;
import com.example.webchar.webchar.pojo.Users;
import com.example.webchar.webchar.service.UserService;
import com.example.webchar.webchar.utils.JwtUtil;
import com.example.webchar.webchar.utils.MailUtils;
import com.example.webchar.webchar.utils.RedisUtils;
import com.example.webchar.webchar.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import java.util.List;

/**
 * @program: webchars
 * @description
 * @author: YouName
 * @create: 2021-08-19 20:28
 **/
@Component
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapperSlave userMapperSlave;
    @Autowired
    private RedisUtils redisUtis;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserMapperMaster userMapperMaster;

    /**
     * 邮件工具
     */
    @Autowired
    private MailUtils mailUtils;

    @Override
    public String toLogin(Users user) {
        Users users = userMapperSlave.loginUser(user.getName(), user.getPassword());
        if (users != null) {
            String token = JwtUtil.sign(users.getId(), users.getName(), users.getPassword());
            redisUtis.set(token, users, 60 * 30);
            return token;
        } else {
            return null;
        }
    }

    /**
     * 注册
     *
     * @param user
     * @param vCode
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result register(Users user, String vCode) {

        List<Users> users = userMapperSlave.queryUsers();
        //查询全部的name信息
        for (Users querUser : users) {
            if (querUser.equals(user.getName())) {
                //判断输入信息里面是否存在相同的user信息
                return Result.fail().add("err", "该账号被注册了,请重新选择");
            }
        }
        String code = redisTemplate.opsForValue().get(user.getEmail());
        //获取存储在redis中的code信息
        if (vCode.equals(code)) {
            try {
                userMapperMaster.insUsers(user);
                userMapperMaster.insRoseUser(user.getId(), "2");
//              roseId为2表示为普通用户 1 为管理员
                log.info(user.getName() + "用户创建成功" + "用户id" + user.getId() + "权限为普通用户");
                return Result.success().add("success", "新建信息成功");
            } catch (Exception e) {
                log.info("数据回滚 出现异常");
                return Result.fail().add("err", "出现异常");
            }
        } else {
            return Result.fail().add("err", "验证码错误");
        }
    }

    /**
     * 设置验证码
     *
     * @param email
     * @return
     */
    @Override
    public Result sendVcode(String email) {

        String code = mailUtils.generatedcode(4);
        //生成4位数的验证码;
        System.out.println(code);
        System.out.println(email);
        try {
            mailUtils.sendMail(email, "请注意验证码信息", code);
            //发送验证码到指定邮箱
            redisTemplate.opsForValue().set(email, code);
            //k:email v:code
            return Result.success().add("success", "验证码发送成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            return Result.fail().add("err", "验证码发送失败");
        }

    }

    /**
     * 测试验证码
     *
     * @return
     */
    public Result testVcode(String vCode) {
        // 获取验证码
        String cacheVcode = redisTemplate.opsForValue().get("USER_V_CODE_" + vCode);
        if (cacheVcode == null && cacheVcode.equals(vCode)) {
            // 未过期的验证码
            return Result.builder().code(false).msg("验证码错误").build();
        }
        return Result.builder().code(true).build();
    }
}
